package com.wdhcr.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/*
 * @description: 腾讯云存储桶的上传工具类
 * @author: wdhcr
 * @dateTime: 2020/3/31 20:24
 */
@Component
public class TencentCOSUtil {

    private static String ACCESSKEY;

    private static String AECRETKEY;

    private static String AREA;

    private static String APP_ID;

    private static String BUCKETNAME;

    private static String URL;

    @Value("${Tencent.ACCESSKEY}")
    public void setACCESSKEY(String ACCESSKEY) {
        TencentCOSUtil.ACCESSKEY = ACCESSKEY;
    }

    @Value("${Tencent.AECRETKEY}")
    public void setAECRETKEY(String AECRETKEY) {
        TencentCOSUtil.AECRETKEY = AECRETKEY;
    }

    @Value("${Tencent.AREA}")
    public void setAREA(String AREA) {
        TencentCOSUtil.AREA = AREA;
    }

    @Value("${Tencent.APP_ID}")
    public void setAppId(String appId) {
        APP_ID = appId;
    }

    @Value("${Tencent.BUCKETNAME}")
    public void setBUCKETNAME(String BUCKETNAME) {
        TencentCOSUtil.BUCKETNAME = BUCKETNAME;
    }

    @Value("${Tencent.URL}")
    public void setURL(String URL) {
        TencentCOSUtil.URL = URL;
    }

    public static COSClient TencentStart() {
        // 指定要上传到的存储桶
        COSCredentials cred = new BasicCOSCredentials(APP_ID, ACCESSKEY, AECRETKEY);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者接口文档 FAQ 中说明。
        ClientConfig clientConfig = new ClientConfig(new Region(AREA));
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        return cosClient;
    }

    public static Map<String, String> uploadFileInTencent(MultipartFile image) {
        COSClient cosClient = TencentCOSUtil.TencentStart();//工具类
        String originalFilename = image.getOriginalFilename();
        String extName = StringUtils.getFilenameExtension(originalFilename);//获取后缀名
        // 指定要上传到 COS 上对象键
        String key = "vblog_" + UUID.randomUUID().toString() + System.nanoTime() + "." + extName;//为接收到的文件命名
        InputStream inputStream = null;
        try {
            inputStream = new ByteArrayInputStream(image.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(image.getSize());
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, key, inputStream, objectMetadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
        cosClient.generatePresignedUrl(BUCKETNAME, key, expiration);
        Map<String, String> urlMap = new HashMap<>();
        urlMap.put("url", URL + "/" + key);
        urlMap.put("key", key);
        return urlMap;
    }

    //根据key删除Cos上的数据
    public static boolean deleteFileInTencent(String key) {
        //获取客户端
        COSClient cosClient = TencentCOSUtil.TencentStart();//工具类
        try {
            //执行删除操作
            cosClient.deleteObject(BUCKETNAME, key);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭客户端
            cosClient.shutdown();
        }
    }
}
